const mongoose = require('mongoose')
const handleE11000 = require('../common/error-handle.api').handleE11000
const Schema = mongoose.Schema

const CounterSchema = new Schema({
  _id: { type: String, required: true }, // _id默认就会给index: 1, 如果重复定义unique: true会出错
  seq: { type: Number, default: 0, min: 0 }
}, {
  versionKey: false,
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
})

// middleware
CounterSchema.post('save', handleE11000)
CounterSchema.post('update', handleE11000)
CounterSchema.post('findOneAndUpdate', handleE11000)
CounterSchema.post('insertMany', handleE11000)

const Counter = mongoose.model('Counter', CounterSchema)

exports = module.exports = Counter
